﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SecureCommander.Helper;
using SecureCommander.GUI;
using System.Collections;
using SecureCommander.Core;
using System.Xml.Serialization;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using SecureCommander.DataAccess;
using SecureCommander.Core.UserManagement;
using Microsoft.Win32;
using System.Data;

namespace SecureCommander
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Properties

        public UCExplorer CurrentExplorer { get; set; }
        private IList explorers = new ArrayList();
        public Hashtable CachePaths { get; set; }
        public ConfigurationData Configuration { get; set; }
        private Brush _selectedTextFieldBackground;
        private Brush _unSelectedTextFieldBackground;
        public Data ApplicationData { get; set; }
        #endregion

        #region Methods

        public MainWindow()
        {
            InitializeComponent();
            LoadConfiguration();
            _selectedTextFieldBackground = (Brush)new BrushConverter().ConvertFrom("#8BA169");
            _unSelectedTextFieldBackground = (Brush)new BrushConverter().ConvertFrom("#F0F0F0");

            ApplicationData = Data.Load();

            explorers.Add(ucExplorer1);
            explorers.Add(ucExplorer2);

            ucExplorer1.MainForm = ucExplorer2.MainForm = this;
            ucExplorer1.OtherExplorer = ucExplorer2;
            ucExplorer2.OtherExplorer = ucExplorer1;

            ucExplorer1.InitPath();
            ucExplorer2.InitPath();

            FileHelper.DisplayExplorer(ucExplorer1);
            FileHelper.DisplayExplorer(ucExplorer2);
            ucExplorer1.lvContent.SelectedIndex = 0;
            ucExplorer1.txtPath.Background = _selectedTextFieldBackground;
            CurrentExplorer = ucExplorer1;
        }

        private void LoadConfiguration()
        {
            Configuration = ConfigurationData.Load();
            CachePaths = Configuration.getCachePathsAsHashtable();
            ucExplorer1.CurrentPartition = Configuration.Partition1;
            ucExplorer2.CurrentPartition = Configuration.Partition2;
        }

        private void RefreshAllExplorers()
        {
            foreach (UCExplorer explorer in explorers)
            {
                FileHelper.DisplayExplorer(explorer);
            }
        }

        private void RefreshAllExplorersExcept(UCExplorer except)
        {
            foreach (UCExplorer explorer in explorers)
            {
                if (!except.Equals(explorer))
                {
                    FileHelper.DisplayExplorer(explorer);
                }
            }
        }

        #endregion

        #region Event Handler

        private void ucExplorer_MouseUp(object sender, MouseButtonEventArgs e)
        {

            if (!sender.Equals(CurrentExplorer))
            {
                if (CurrentExplorer != null)
                {
                    CurrentExplorer.txtPath.Background = _unSelectedTextFieldBackground;
                }

                CurrentExplorer = (UCExplorer)sender;
                var bc = new BrushConverter();
                CurrentExplorer.txtPath.Background = _selectedTextFieldBackground;
            }

            if (e == null)
            {
                return;
            }

            ListViewContent item = (ListViewContent)((FrameworkElement)e.OriginalSource).DataContext;
            if (item == null)
            {
                CurrentExplorer.lvContent.SelectedIndex = -1;
            }

        }

        private void mnNewFolder_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.NewFolder(CurrentExplorer);
            RefreshAllExplorersExcept(CurrentExplorer);
        }

        private void mnNewText_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.NewTextDocument(CurrentExplorer);
            RefreshAllExplorersExcept(CurrentExplorer);
        }

        private void mnNewWord_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.NewWordDocument(CurrentExplorer);
            RefreshAllExplorersExcept(CurrentExplorer);
        }

        private void mnPack_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.Pack(CurrentExplorer);
        }

        private void mnUnPack_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.UnPack(CurrentExplorer);
        }

        private void mnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.Delete(CurrentExplorer);
            RefreshAllExplorersExcept(CurrentExplorer);
        }

        private void mnRename_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.Rename(CurrentExplorer);
            RefreshAllExplorersExcept(CurrentExplorer);
        }

        private void mnProperties_Click(object sender, RoutedEventArgs e)
        {

            if (CurrentExplorer == null)
            {
                return;
            }
            NativeMethods.ShowFileProperties(((ListViewContent)CurrentExplorer.lvContent.SelectedItem).Tag.FullName);

        }

        private void mnExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void mnCopy_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.Copy(CurrentExplorer, CurrentExplorer.OtherExplorer);
        }

        private void mnSeleteAll_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.SelectedAll(CurrentExplorer);
        }

        private void mnRefresh_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentExplorer == null)
            {
                return;
            }
            FileHelper.Refresh(CurrentExplorer);
        }

        private void SecureCommander_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Configuration.UpdateCachePaths(CachePaths);
            Configuration.Partition1 = ucExplorer1.CurrentPartition;
            Configuration.Partition2 = ucExplorer2.CurrentPartition;

            Configuration.Save();

            ApplicationData.Save();
        }

        private void SecureCommander_KeyUp(object sender, KeyEventArgs e)
        {
            if (e == null)
            {
                return;
            }
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && e.Key == Key.R)
            {
                FileHelper.Refresh(CurrentExplorer);
                return;
            }
            switch (e.Key)
            {
                case Key.F1:
                    //this.Encrypt();
                    break;
                case Key.F2:
                    //this.Decrypt();
                    FileHelper.Rename(CurrentExplorer);
                    break;
                case Key.F3:
                    //this.Sign();
                    break;
                case Key.F4:
                    //this.VerifySignature();
                    break;
                case Key.F5:
                    FileHelper.Copy(CurrentExplorer, CurrentExplorer.OtherExplorer);
                    break;
                case Key.F7:
                    FileHelper.NewFolder(CurrentExplorer);
                    break;
                case Key.F8:
                    FileHelper.Delete(CurrentExplorer);
                    break;
                case Key.Delete:
                    FileHelper.Delete(CurrentExplorer);
                    break;
                case Key.Back:
                    if (CurrentExplorer.CurrentDirectory != Directory.GetDirectoryRoot(CurrentExplorer.CurrentDirectory))
                    {
                        CurrentExplorer.CurrentDirectory = ((ListViewContent)CurrentExplorer.lvContent.Items[0]).Tag.FullName;
                        FileHelper.DisplayExplorer(CurrentExplorer);
                    }
                    break;
                case Key.Enter:
                    if (e != null)
                    {
                        ListViewContent item = (ListViewContent)((FrameworkElement)e.OriginalSource).DataContext;
                        if (item != null)
                        {
                            FileHelper.OpenItem(CurrentExplorer, item);
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        private void mnSignUp_Click(object sender, RoutedEventArgs e)
        {
            FormRegisterUser frm = new FormRegisterUser();
            frm.Users = ApplicationData.Users;
            if (frm.ShowDialog().Value)
            {
                ApplicationData.Users.Add(frm.User);
                ApplicationData.Save();
            }
        }

        private void mnUpdateUserInfo_Click(object sender, RoutedEventArgs e)
        {
            FormLogin frm = new FormLogin();
            frm.Users = ApplicationData.Users;
            if (frm.ShowDialog().Value)
            {
                UserInfo user = frm.LoginedUser;
                FormRegisterUser frmUpdateUser = new FormRegisterUser();
                frmUpdateUser.Users = ApplicationData.Users;
                frmUpdateUser.Title = "Update User";
                frmUpdateUser.IsUpdate = true;
                frmUpdateUser.User = user;
                if (frmUpdateUser.ShowDialog().Value)
                {
                    ApplicationData.Save();
                    FileHelper.ShowMessage("Update user '" + user.Mail + "' success!", MessageBoxImage.Information);
                }
            }
        }

        private void mnImport_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog opendia = new OpenFileDialog();
            opendia.Filter = "XML|*.xml";
            if (opendia.ShowDialog().Value)
            {
                UserInfo user = UserManager.Import(opendia.FileName);
                FormRegisterUser frm = new FormRegisterUser();
                frm.Users = ApplicationData.Users;
                frm.IsImport = true;
                frm.Title = "Import user";
                frm.User = user;
                if (frm.ShowDialog().Value)
                {
                    ApplicationData.Users.Add(user);
                    ApplicationData.Save();
                    FileHelper.ShowMessage("Import user '" + user.Mail + "' success!", MessageBoxImage.Information);
                }
            }
        }

        private void mnExport_Click(object sender, RoutedEventArgs e)
        {
            FormLogin frm = new FormLogin();
            frm.Users = ApplicationData.Users;
            if (frm.ShowDialog().Value)
            {
                UserInfo user = frm.LoginedUser;

                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.InitialDirectory = CurrentExplorer.CurrentDirectory;
                saveDialog.Filter = "XML|*.xml";
                if (saveDialog.ShowDialog().Value)
                {
                    if (UserManager.Export(user, saveDialog.FileName))
                    {
                        FileHelper.ShowMessage("Export user '" + user.Mail + "' success!", MessageBoxImage.Information);
                    }
                }
            }
            FileHelper.DisplayExplorer(CurrentExplorer.OtherExplorer);
            FileHelper.DisplayExplorer(CurrentExplorer);
        }

        public void mnEncrypt_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FormEncrypt frm = new FormEncrypt();
                frm.StartDirectory = CurrentExplorer.CurrentDirectory;
                foreach (ListViewContent item in CurrentExplorer.lvContent.SelectedItems)
                {
                    if (item.Name != "...")
                    {
                        frm.gridSelectedFiles.Items.Add(item);
                    }
                }
                if (frm.ShowDialog().Value)
                {
                    FileHelper.ShowMessage("Encrypt success!", MessageBoxImage.Information);
                }
            }
            catch (Exception)
            {
                FileHelper.ShowMessage("Can not ecrypt all selected files/folders!", MessageBoxImage.Error);
            }

            FileHelper.DisplayExplorer(CurrentExplorer.OtherExplorer);
            FileHelper.DisplayExplorer(CurrentExplorer);
        }

        public void mnDecrypt_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (CurrentExplorer.lvContent.SelectedItems.Count <= 0)
                {
                    FileHelper.ShowMessage("No file selected!", MessageBoxImage.Warning);
                    return;
                }
                if (CurrentExplorer.lvContent.SelectedItems.Count > 1)
                {
                    FileHelper.ShowMessage("Please choose just 1 file/folder!", MessageBoxImage.Warning);
                    return;
                }
                ListViewContent item = (ListViewContent) CurrentExplorer.lvContent.SelectedItems[0];
                if (item.Tag.Extension.ToUpper() != ".ENC")
                {
                    FileHelper.ShowMessage("Please choose encrypted file!", MessageBoxImage.Warning);
                    return;
                }

                FormLogin frm = new FormLogin();
                frm.Users = Data.ApplicationData.Users;
                if (frm.ShowDialog().Value)
                {
                    FormDecrypt decrypt = new FormDecrypt();
                    decrypt.Passphrase = frm.txtPassword.Password;
                    decrypt.User = frm.LoginedUser;
                    if(decrypt.ShowDialog().Value) {
                        FileHelper.DisplayExplorer(CurrentExplorer.OtherExplorer);
                        FileHelper.DisplayExplorer(CurrentExplorer);
                    }
                }
            }
            catch(Exception ex)
            {
                FileHelper.ShowMessage(ex.Message, MessageBoxImage.Error);
            }
        }

        public void mnSign_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FormLogin frm = new FormLogin();
                frm.Users = Data.ApplicationData.Users;
                if (frm.ShowDialog().Value)
                {
                    FormSign signature = new FormSign();
                    signature.Passphrase = frm.txtPassword.Password;
                    signature.User = frm.LoginedUser;
                    signature.StartDirectory = CurrentExplorer.CurrentDirectory;
                    if (signature.ShowDialog().Value)
                    {
                        FileHelper.DisplayExplorer(CurrentExplorer.OtherExplorer);
                        FileHelper.DisplayExplorer(CurrentExplorer);
                    }
                }
            }
            catch (Exception ex)
            {
                FileHelper.ShowMessage(ex.Message, MessageBoxImage.Error);
            }
        }

        public void mnVerify_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FormLogin frm = new FormLogin();
                frm.Users = Data.ApplicationData.Users;
                if (frm.ShowDialog().Value)
                {
                    FormVerifySignature signature = new FormVerifySignature();
                    signature.Title = "Signature verification";
                    signature.btnOK.Content = "Verify";
                    signature.Passphrase = frm.txtPassword.Password;
                    signature.User = frm.LoginedUser;
                    signature.StartDirectory = CurrentExplorer.CurrentDirectory;
                    signature.Users = Data.ApplicationData.Users;
                    if (signature.ShowDialog().Value)
                    {
                        FileHelper.DisplayExplorer(CurrentExplorer.OtherExplorer);
                        FileHelper.DisplayExplorer(CurrentExplorer);
                    }
                }
            }
            catch (Exception ex)
            {
                FileHelper.ShowMessage(ex.Message, MessageBoxImage.Error);
            }
        }

        private void mnAbout_Click(object sender, RoutedEventArgs e)
        {
            frmAbout frm = new frmAbout();
            frm.Show();
        }

        #endregion

    }
}
